<?php

class Res extends Mysql {
	public function __construct() {
		parent::__construct ();
	}
	
/**
	 * 上传一个资源之后，添加数据库记录（时间用mysql方法NOW()）
	 * 
	 * @param $name 名称        	
	 * @param $path 路径        	
	 * @param $type 类型        	
	 * @param $size 文件大小     
	 * @param $tagId 标签id   	
	 */
	public function add($name, $path, $type, $size, $tagId) {
		$sql = "insert into res(name, path, time, type, size, tagId) values ('$name', '$path', NOW(), '$type', $size, $tagId);";
		return $this->exec_update ( $sql );
	}
	
	/**
	 * 删除一个资源；
	 *
	 * @param $id 资源id
	 */
	public function delete($id) {
		$sql = "delete from res where id = $id";
		return $this->exec_update($sql);
	}
	
	/**
	 * 根据tagid查询资源，分页
	 *
	 * @param $tagName 资源标签
	 * @param $pageIndex 当前页
	 * @param $pageSize 页大小（默认常数RES_PAGE_SIZE）
	 */
	public function query($tagId, $pageIndex = 0, $pageSize = RES_PAGE_SIZE) {
		if (empty ( $pageIndex ) || ltrim ( $pageIndex ) == '') {
			$pageIndex = 0;
		}
		if (empty ( $pageSize ) || ltrim ( $pageSize ) == '') {
			$pageSize = RES_PAGE_SIZE;
		}
		$start = $pageIndex * $pageSize;
		$sql = "";
	if (empty ( $tagId ) || ltrim ( $tagId ) == '') {
			$sql = "select res.*,restag.name as tagName,count(res.id) as loadNum from res left join resload on res.id=resload.resid join restag on res.tagid= restag.id group by res.id
	 LIMIT $start, $pageSize; ";
		
		} else {
			$sql = "select res.*, restag.name as tagName, count(res.id) as loadNum from res left join resload on res.id=resload.resid join restag on res.tagid = restag.id where  restag.id  = $tagId order by  res.time desc LIMIT $start, $pageSize;";
		}
		$rows = $this->exec_query ( $sql );
		return $rows;
	
	}
	/**
	 * 计数
	 * @param unknown_type $articleTypeId
	 */
	public function count($tagId) {
		$sql = "";
		//类型为空，则查询全部的
		if (empty($tagId) || ltrim($tagId)=='') {
			$sql = "select COUNT(res.id) as num FROM res;";
		}
		else {
			$sql = "select COUNT(res.id) as num FROM res where tagId = $tagId;";
		}
		$rows = $this->exec_query($sql);
		if ($rows && count($rows) > 0) {//返回第一个集合
			return $rows[0][num];//返回num字段
		}
		return 0;
	}
	/**
	 * 更新一个资源（资源路径不能修改，因为涉及到上传，麻烦）
	 * 
	 * @param $id 资源id        	
	 * @param $name 资源新名称        	
	 * @param $type 资源新类型    
	 * @param $tagId 资源标签    	
	 */
	public function update($id, $name, $type, $tagId) {
		$sql = "update res set name = '$name', type = '$type', tagId = $tagId, where id = $id;";
		return $this->exec_update ( $sql );
	}
	public function querybyid($tagId, $id) {
		$sql = "select res.*,restag.name as tagName from res left join restag on res.tagid= restag.id  where res.id =$id  group by res.id;";
	
		$rows = $this->exec_query ( $sql );
		return $rows;
	}
}

?>